/*
 * Copyright (c) 2014-2015 Luca Agostini, Alessandro Cantini, Alessandro Dignani
 *
 * This file is part of MeteoCal.
 *
 * MeteoCal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.polimi.se2.agostini_cantini_dignani.meteocal.util;

import org.apache.commons.lang3.time.DateUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by alessandrodignani on 24/01/15.
 */
public class DateTimeUtils {
	private DateTimeUtils() {
	}

	public static String format(Date date, String pattern, String timeZone) {
		SimpleDateFormat converter = new SimpleDateFormat(pattern);
		converter.setTimeZone(TimeZone.getTimeZone(timeZone));

		return converter.format(date);
	}

	/**
	 * Returns the absolute difference  between two dates
	 *
	 * @param d1 the first date
	 * @param d2 the second date
	 * @return the absolute difference between the given dates
	 */
	public static int distanceInDays(Date d1, Date d2) {
		if (d1.after(d2)) {
			return distanceInDays(d2, d1);
		}

		int daysElapsed = (int) ((d2.getTime() - d1.getTime()) / (DateUtils.MILLIS_PER_DAY));

		Calendar cal1 = DateUtils.toCalendar(d1);
		Calendar cal2 = DateUtils.toCalendar(d2);
		cal2.set(Calendar.YEAR, cal1.get(Calendar.YEAR));
		cal2.set(Calendar.DAY_OF_YEAR, cal1.get(Calendar.DAY_OF_YEAR));
		Date temp2 = cal2.getTime();

		if (temp2.getTime() >= d1.getTime()) {
			return daysElapsed;
		}
		return daysElapsed + 1;
	}
}
